﻿using System;
using System.Reflection;
using System.Configuration;

namespace JCode.DALFactory
{
    /// <summary>
    /// Abstract Factory pattern to create the DAL。
    /// 如果在这里创建对象报错，请检查web.config里是否修改了<add key="DAL" value="Maticsoft.SQLServerDAL" />。
    /// </summary>
    public sealed class DataAccess
    {
        private static readonly string AssemblyPath = ConfigurationManager.AppSettings["DAL"];
        public DataAccess()
        { }

        #region CreateObject

        //不使用缓存
        private static object CreateObjectNoCache(string AssemblyPath, string classNamespace)
        {
            try
            {
                object objType = Assembly.Load(AssemblyPath).CreateInstance(classNamespace);
                return objType;
            }
            catch//(System.Exception ex)
            {
                //string str=ex.Message;// 记录错误日志
                return null;
            }

        }
        //使用缓存
        private static object CreateObject(string AssemblyPath, string classNamespace)
        {
            object objType = DataCache.GetCache(classNamespace);
            if (objType == null)
            {
                try
                {
                    objType = Assembly.Load(AssemblyPath).CreateInstance(classNamespace);
                    DataCache.SetCache(classNamespace, objType);// 写入缓存
                }
                catch(Exception e)//(System.Exception ex)
                {
                   
                    //string str=ex.Message;// 记录错误日志
                }
            }
            return objType;
        }
        #endregion





        /// <summary>
        /// 创建Category数据层接口
        /// </summary>
        public static JCode.IDAL.ICategory CreateCategory()
        {

            string ClassNamespace = AssemblyPath + ".Category";
            object objType = CreateObject(AssemblyPath, ClassNamespace);
            return (JCode.IDAL.ICategory)objType;
        }

        public static JCode.IDAL.ICode CreateCode()
        {

            string ClassNamespace = AssemblyPath + ".Code";
            object objType = CreateObject(AssemblyPath, ClassNamespace);
            return (JCode.IDAL.ICode)objType;
        }
    }
}
